

// koa
const Koa = require('koa');
const app = new Koa();

const Router = require('koa-router');
const router = new Router();

const {sign} = require('jsonwebtoken');
const secret = 'demo';
const jwt = require('koa-jwt')({secret:secret});
const bodyParser = require('koa-bodyparser');

const static = require('koa-static');

// admin middle
const admin = async (ctx,next)=>{
    if(ctx.state.user.username === 'admin'){
        next();
    }else{
        ctx.body = {
            code:-1,
            message:'Auth Error!'
        }
    }
};

///
router.post('/api/login',async (ctx,next)=>{
   const user = ctx.request.body;
   if(user && user.username){
       let username = user.username;
       // 生成token
       const token = sign({username:username},secret,{expiresIn:'1h'});
       ctx.body = {
           message:'Get token success!',
           code:1,
           token:token
       }
   }else{
       ctx.body = {
           message:'Param Error',
           code:-1,
       }
   }
})
    .get('/api/userInfo',jwt,async ctx=>{
    ctx.body = {
        username:ctx.state.user.username
    }
}).get('/api/adminInfo',jwt,admin,async ctx=>{
    ctx.body = {
        username:ctx.state.user.username
    }
});


app.use(bodyParser());
app.use(static(__dirname+'/static'));
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000,()=>{
    console.log('server is running at http://localhost:3000');
});


//////
// const user = new Router(); // 主路由
// const detail = new Router(); // 嵌套路由
//
//
// detail.get('/info',async ctx=>{
//     ctx.body = {
//         username:ctx.state.user.username
//     }
// });
//
// user.get('/api/login',async (ctx,next)=>{
//
// });
